package org.raymond.iworks.study.basic.designpattern.proxy.cglib;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * @author raymond
 * @version V1.0
 * @Description: TODO
 */
public class ProxyFactory implements MethodInterceptor {
    private Object target;
    public ProxyFactory(Object target){
        this.target = target;
    }

    /**
     * 返回target的代理对象
     * @return
     */
    public Object getProxyInstance(){
        /**
         * 1, 创建一个工具类
         * 2, 设置父类
         * 3, 设置回调函数
         * 4, 创建子类对象,即代理对象
         */
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(target.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

    /**
     * 重写intercept方法,会调用目标对象的方法
     */
    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        System.out.println("cglib代理模式开始: target:"+target.toString());
        Object returnVal = method.invoke(target, args);
        System.out.println("cglib代理提交");
        return returnVal;
    }
}
